package com.sskj.wechat.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.sskj.core.exception.MException;
import com.sskj.core.util.JsonUtil;
import com.sskj.wechat.domain.ConfigQueryParam;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@RequestMapping("/wechat")
public class WeChatAuthServiceImpl {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private WxMpService wxService;

	@Autowired
	private WxMpMessageRouter router;

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/get/user", method = { RequestMethod.GET })
	@ApiImplicitParams({ @ApiImplicitParam(name = "code", value = "关键字", paramType = "form", dataType = "string") })
	public WxMpUser getWxMpUser(@ApiIgnore ConfigQueryParam contfigQueryParam) {
		System.out.println(contfigQueryParam.getCode());
		WxMpUser wxMpUser = null;
		try {

			WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxService.oauth2getAccessToken(contfigQueryParam.getCode());

			wxMpUser = wxService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);

		} catch (WxErrorException e) {
			this.logger.info("\n WxErrorException：{}", JsonUtil.json(e));

			Object[] msg = { e.getError().getErrorMsg() };
			throw new MException("custom_msg", msg);
		}

		this.logger.info("\n wxMpUser：{}", JsonUtil.json(wxMpUser));
		return wxMpUser;

	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/api/sign", method = { RequestMethod.POST })
	public WxJsapiSignature getConfig(@RequestBody ConfigQueryParam contfigQueryParam) {

		try {
			WxJsapiSignature ws = wxService.createJsapiSignature(contfigQueryParam.getUrl());

			this.logger.info("\n Config：{}", JsonUtil.json(ws));

			return ws;
		} catch (WxErrorException e) {
			e.printStackTrace();
			throw new MException("");
		}
	}

	@RequestMapping(value = "/portal", method = { RequestMethod.GET }, produces = "text/plain;charset=utf-8")
	public String authGet(@RequestParam(name = "signature", required = false) String signature,
			@RequestParam(name = "timestamp", required = false) String timestamp,
			@RequestParam(name = "nonce", required = false) String nonce,
			@RequestParam(name = "echostr", required = false) String echostr) {

		this.logger.info("\n接收到来自微信服务器的认证消息：[{}, {}, {}, {}]", signature, timestamp, nonce, echostr);

		if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
			throw new IllegalArgumentException("请求参数非法，请核实!");
		}

		if (this.wxService.checkSignature(timestamp, nonce, signature)) {
			return echostr;
		}

		return "非法请求";
	}

	@RequestMapping(value = "/portal", method = { RequestMethod.POST }, produces = "application/xml; charset=UTF-8")
	public String post(@RequestBody String requestBody, @RequestParam("signature") String signature,
			@RequestParam("timestamp") String timestamp, @RequestParam("nonce") String nonce,
			@RequestParam(name = "encrypt_type", required = false) String encType,
			@RequestParam(name = "msg_signature", required = false) String msgSignature) {
		this.logger.info(
				"\n接收微信请求：[signature=[{}], encType=[{}], msgSignature=[{}],"
						+ " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
				signature, encType, msgSignature, timestamp, nonce, requestBody);

		if (!this.wxService.checkSignature(timestamp, nonce, signature)) {
			throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
		}

		String out = null;
		if (encType == null) {
			// 明文传输的消息
			WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
			WxMpXmlOutMessage outMessage = this.route(inMessage);
			if (outMessage == null) {
				return "";
			}

			out = outMessage.toXml();
		} else if ("aes".equals(encType)) {
			// aes加密的消息
			WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody,
					this.wxService.getWxMpConfigStorage(), timestamp, nonce, msgSignature);
			this.logger.debug("\n消息解密后内容为：\n{} ", inMessage.toString());
			WxMpXmlOutMessage outMessage = this.route(inMessage);
			if (outMessage == null) {
				return "";
			}

			out = outMessage.toEncryptedXml(this.wxService.getWxMpConfigStorage());
		}

		this.logger.debug("\n组装回复信息：{}", out);

		return out;
	}

	private WxMpXmlOutMessage route(WxMpXmlMessage message) {
		try {
			return this.router.route(message);
		} catch (Exception e) {
			this.logger.error(e.getMessage(), e);
		}

		return null;
	}

}
